package fragment;

import holder.ItemHolder;

import java.util.List;
import java.util.Random;

import manager.DownLoadManager;

import factory.ListViewFactory;

import protocol.GameProtocol;

import base.BaseFragment;
import base.BaseHolder;
import base.BaseItemAdapter;
import base.LoadingPager.LoadResult;
import base.SuperBaseAdapter;
import bean.AppInfoBean;
import utils.UIUtils;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;

public class GameFragment extends BaseFragment {

	private GameProtocol gameProtocol;
	private List<AppInfoBean> mDatas;
	private GameAdapter madapter;

	/**
	 * 
	 * 
	 */
	@Override
	protected LoadResult initData() {
		SystemClock.sleep(2000);
		//成功
		//失败
		//错误
		
		gameProtocol = new GameProtocol();
		try {
			mDatas = gameProtocol.loadData(0);
			return checkState(mDatas);
		} catch (Exception e) {
			e.printStackTrace();
			return LoadResult.ERROR;
		}
		
	}

	@Override
	protected View initSuccessView() {
		ListView listView = new ListViewFactory().createListView();
		//设置适配器
		madapter = new GameAdapter(listView, mDatas);
		listView.setAdapter(madapter);
		return listView;
	}
	
	class GameAdapter extends BaseItemAdapter{

		public GameAdapter(AbsListView ablistView, List<AppInfoBean> mDatas) {
			super(ablistView, mDatas);
			// TODO Auto-generated constructor stub
		}

		/**
		 * 加载更多的数据
		 */
		@Override
		protected List<AppInfoBean> onLoadMore() throws Exception {
			// TODO Auto-generated method stub
			return gameProtocol.loadData(mDatas.size());
		}
	}
	
	@Override
	public void onPause() {
		if (madapter != null) {
			// 移除观察者
			List<ItemHolder> getmItemHolders = madapter.getmItemHolders();
			for (int i = 0; i < getmItemHolders.size(); i++) {

				DownLoadManager.getInstance()
						.deleteObserver(getmItemHolders.get(i));
			}
		}
		
		super.onPause();
	}

	@Override
	public void onResume() {
		if (madapter != null) {
			// 添加观察者
			List<ItemHolder> mItemHolders = madapter.getmItemHolders();
				for (int i = 0; i < mItemHolders.size(); i++) {
					DownLoadManager.getInstance()
					.addObserver(mItemHolders.get(i));
				}
				
			madapter.notifyDataSetChanged();
		}
		
		super.onResume();
	}

}
